package com.example.pet.controller;

import com.example.pet.dao.UserDao;
import com.example.pet.entity.User;
import com.example.pet.util.Response;
import com.example.pet.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserDao userDao;

    @PostMapping("/user/login")
    @ResponseBody
    public Response login(@RequestParam String username, @RequestParam String password) {
        User dbUser = userDao.getByTwoField(User::getUsername,username,User::getPassword,password);
        if (dbUser != null) {
            //login success
            SessionUtil.setUser(dbUser);
            return Response.success();
        }else {
            return Response.fail("用户名或密码错误");
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        SessionUtil.logout();
        return "login";
    }

    @PostMapping("/user/register")
    @ResponseBody
    public Response register(User user) {
        if (StringUtils.hasLength(user.getUsername()) && StringUtils.hasLength(user.getPassword()) && StringUtils.hasLength(user.getQq())) {
            User dbUser = userDao.getByOneField(User::getUsername,user.getUsername());
            if (dbUser == null) {
                int result = userDao.insert(user);
                if (result > 0) {
                    SessionUtil.setUser(user);
                    return Response.success();
                }else {
                    return Response.fail("注册失败");
                }
            }else {
                return Response.fail("用户已存在");
            }
        }else {
            return Response.fail("输入不正确");
        }
    }

    @PostMapping("/user/updatePassword")
    @ResponseBody
    public Response updatePassword(@RequestParam String username,@RequestParam String qq, @RequestParam String newPassword) {
        User user = userDao.getByOneField(User::getUsername,username);
        if (user != null) {
            if (qq.equals(user.getQq())) {
                User dbUser = new User();
                dbUser.setId(user.getId());
                dbUser.setPassword(newPassword);
                userDao.updateById(dbUser);
                return Response.success();
            }else {
                return Response.fail("QQ号不正确");
            }
        }
        return Response.fail("用户不存在");
    }

}
